﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleData.ObjectModel
{
	internal static class DocumentTokenHelper
	{
		private static readonly Random rnd = new Random( System.Diagnostics.Process.GetCurrentProcess().Id );
		private static readonly Random rnd2 = new Random( 2 );

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public static ushort GetRandomID()
		{
			return ( ushort )rnd.Next( UInt16.MinValue, UInt16.MaxValue );
		}

		public static ushort GetRandomID2()
		{
			return ( ushort )rnd2.Next( UInt16.MinValue, UInt16.MaxValue );
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public static char[] TokenChars()
		{
			int lowerLetter = ( int )'A';
			int higherLetter = ( int )'Z';
			int letterCount = higherLetter - lowerLetter + 1;

			int lowerDigit = ( int )'0';
			int higherDigit = ( int )'9';
			int digitCount = higherDigit - lowerDigit + 1;

			char[] chars = new char[ letterCount + digitCount ];

			// Preenche os valores numericos
			for ( int i = 0; i < digitCount; i++ )
				chars[ i ] = ( char )( i + lowerDigit );

			// Preenche os alfa-numericos
			for ( int i = 0; i < letterCount; i++ )
				chars[ i + digitCount ] = ( char )( i + lowerLetter );
			return chars;
		}


		public static IEnumerable<char> ConvertToChar( int value )
		{
			return ConvertToChar( ( ulong )value );
		}

		public static IEnumerable<char> ConvertToChar( long value )
		{
			ulong result = ( ulong )( ( value >> 32 ) & UInt32.MaxValue );
			result <<= 32;
			result |= ( ulong )( value & UInt32.MaxValue );

			return ConvertToChar( result );
		}

		/// <summary>
		/// Converte o número <paramref name="value"/> para uma sequência de caracteres
		/// que representa o número
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
		public static IEnumerable<char> ConvertToChar( ulong value )
		{
			List<char> token = new List<char>();
			uint len = ( uint )DocumentToken.ValidTokenChars.Length;

			while ( value >= len )
			{
				ushort index = ( ushort )( value % len );
				value /= len;

				yield return DocumentToken.ValidTokenChars[ index ];
			}

			yield return DocumentToken.ValidTokenChars[ value ];
		}
	}
}
